/**
 * @class MapService.Control.SaveMapViewExtent
 * @extends OpenLayers.Control
 * Salva a última visualização do mapa em cookie.
 * 
 * Sempre que a aplicação e iniciada o mapa e reposicionado para a última visualização.
 * 
 * Exemplo de uso:
 * 
 *     mapService.map.addControl(new MapService.Control.SaveMapViewExtent());
 *     
 */
MapService.Control.SaveMapViewExtent = OpenLayers.Class(OpenLayers.Control, {
	autoActivate: true,
	
    saveMapState: function(map){
    	var me = this;
    	
    	if(me.baseLayer == map.baseLayer){
    		var extent = map.getExtent().clone();
    		extent = extent.transform(map.getProjection(), 'EPSG:4326');
    		
    		me.mapstate = extent.toString();
        	me.createCookie("mapstate", me.mapstate, 360);
    	}
    },
    
    restoreMapState: function(map){
    	var me = this;
    	
    	//if(me.baseLayer != undefined){
    		var extent = OpenLayers.Bounds.fromString(me.mapstate);
    		extent = extent.transform('EPSG:4326', map.getProjection());
    			
   			map.zoomToExtent(extent);
   			
   			//força atualização do mapa.
   			map.setCenter(map.getCenter(), map.zoom, true, true);
    	//}
    	
    	me.baseLayer = map.baseLayer;
    },
    
	setMap: function(map) {
		var me = this;
		
        OpenLayers.Control.prototype.setMap.apply(me, arguments);
	        
        me.mapstate = me.readCookie("mapstate");
        if(me.mapstate == undefined){
        	me.mapstate = mapService.home.toString();
        }
    	
        map.events.register('moveend', me, function(event){
        	me.saveMapState(map);
        });
        
        map.events.register('changebaselayer', me, function(event){
        	me.restoreMapState(map);
		});
    },
    
    createCookie: function(name,value,days) {
    	var expires = "";
    	if(days){
    		var date = new Date();
    		date.setTime(date.getTime()+(days*24*60*60*1000));
    		expires = "; expires="+date.toGMTString();
    	}
    	document.cookie = name + "=" + value + expires + "; path=/";
    },
    
    readCookie: function(name) {
    	var nameEQ = name + "=";
    	var ca = document.cookie.split(';');
    	for(var i=0; i < ca.length; i++) {
    		var c = ca[i];
    		while (c.charAt(0)==' ') c = c.substring(1,c.length);
    		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    	}
    	return null;
    },
    
    eraseCookie: function(name) {
    	createCookie(name,"",-1);
    },

    CLASS_NAME: "MapService.Control.SaveMapViewExtent"
});